package cn.xinyangtong.manager.service.impl;

import cn.xinyangtong.common.util.ConstantsUtil;
import cn.xinyangtong.manager.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 图片上传
 * Created by fengbo on 2017/6/9.
 */
@Service("pictureService")
public class PictureServiceImpl implements PictureService {

    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;

    private enum IsError {
        IS_SUCCESS(0), IS_ERROR(1);
        private int status;
        IsError(int status) {
            this.status = status;
        }

        public int getStatus() {
            return this.status;
        }

    }

    // 通过ftp上传图片
    @Override
    public Map<String, Object> uploadPicture(MultipartFile uploadFile) {
        final Map<String, Object> resultMap = new HashMap<>();
//        final SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/mm/dd");
//        try {
//            String oldName = uploadFile.getOriginalFilename();//获取原文件名
//            String newName = genImageName()+oldName.substring(oldName.lastIndexOf("."));
//            String imagePath = sdf.format(System.currentTimeMillis());
//            //图片上传
//            final boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, //
//                    FTP_PASSWORD, FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
//            if (!result) {
//                resultMap.put("error", IsError.IS_ERROR.getStatus());
//                resultMap.put("message", "文件上传失败！");
//            }
//            resultMap.put("error", IsError.IS_SUCCESS.getStatus());
//            resultMap.put("url", ConstantsUtil.IMAGE_BASE_URL + imagePath + "/" + newName);
//        } catch (Exception e) {
//            resultMap.put("error", IsError.IS_ERROR.getStatus());
//            resultMap.put("message", "文件上传发生异常！");
//        }
        return resultMap;
    }
    /**
     * 图片名生成
     */
    private String genImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);
        return str;
    }
}
